package com.android.lovely.aav.lifecycle

import com.android.lovely.api.service.UserService
import com.android.lovely.api.service.userService
import com.android.lovely.data.LifecycleInfo
import com.android.lovely.data.LovelyLifecycle
import com.android.lovely.framework.doContinuousOperation
import com.android.lovely.manager.KVStore
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.coroutine.applicationScope
import kotlinx.coroutines.Job
import kotlin.collections.isNotEmpty
import kotlin.text.isNullOrEmpty

object LovelyLifecycleManager {

    private val lifecycleDataManager = LifecycleDataManager(userService)
    private val lifecycleDataStore = LifecycleDataStore()
    private val lifecycleInitializer = LifecycleInitializer(lifecycleDataManager, lifecycleDataStore)

    val lovelyLifecycle: List<LovelyLifecycle>
        get() = lifecycleDataStore.lovelyLifecycle

    val lifecycleInfo: LifecycleInfo?
        get() = lifecycleDataStore.lifecycleInfo

    fun isEnable() = lifecycleInfo?.vipProductId.isNullOrEmpty().not() && lovelyLifecycle.isNotEmpty()

    fun init() {
        lifecycleInitializer.init()
    }
}

class LifecycleDataManager(private val userService: UserService) {

    var lovelyLifecycle: List<LovelyLifecycle> = emptyList()
        private set

    var lifecycleInfo: LifecycleInfo? = null
        private set

    suspend fun fetchLovelyLifecycle(): List<LovelyLifecycle> {
        return userService.getLovelyLifecycle().also { lovelyLifecycle = it }
    }

    suspend fun fetchLifecycleInfo(): LifecycleInfo? {
        return userService.getLifecycleInfo().also { lifecycleInfo = it }
    }
}

class LifecycleDataStore {

    var lovelyLifecycle: List<LovelyLifecycle>
        get() = KVStore.lovelyLifecycle
        set(value) {
            KVStore.lovelyLifecycle = value
        }

    var lifecycleInfo: LifecycleInfo?
        get() = KVStore.lifecycleInfo
        set(value) {
            KVStore.lifecycleInfo = value
        }
}

class LifecycleInitializer(
    private val lifecycleDataManager: LifecycleDataManager,
    private val lifecycleDataStore: LifecycleDataStore
) {

    var configJob: Job? = null
    var priceJob: Job? = null

    fun init() {
        if (configJob?.isActive != true) {
            configJob = applicationScope.launchSafety {
                doContinuousOperation {
                    val fetchedLifecycle = lifecycleDataManager.fetchLovelyLifecycle()
                    lifecycleDataStore.lovelyLifecycle = fetchedLifecycle
                }
            }
        }
        if (priceJob?.isActive != true) {
            priceJob = applicationScope.launchSafety {
                doContinuousOperation {
                    val fetchedInfo = lifecycleDataManager.fetchLifecycleInfo()
                    lifecycleDataStore.lifecycleInfo = fetchedInfo
                }
            }
        }
    }
}

